package cn.faster.sys.controller;

import cn.faster.common.constants.Constants;
import cn.faster.common.enums.CodeEnum;
import cn.faster.common.result.AjaxResult;
import cn.faster.common.result.ResultBean;
import cn.faster.common.sign.Base64;
import cn.faster.common.utils.sys.redis.RedisCacheUtils;
import cn.faster.common.utils.sys.uuid.IdUtils;
import cn.faster.sys.entity.SysUser;
import cn.faster.sys.model.LoginBody;
import cn.faster.sys.service.SysLoginService;
import cn.faster.sys.service.SysShiroService;
import cn.faster.sys.service.SysUserService;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * description: SysShiroController
 * date: 2021/6/9 13:37
 * author: XiaoCoder
 * version: 1.0
 */
@RestController
@Api(value = "用户状态接口API", tags = "用户状态接口API")
@RequestMapping("/shiro/userStatus")
@AllArgsConstructor
@CrossOrigin("*")
public class SysLoginController {

    private final DefaultKaptcha defaultKaptcha;
    private final SysUserService sysUserService;
    private final RedisCacheUtils redisCache;
    private final SysShiroService shiroService;
    private final SysLoginService sysLoginService;

    @ApiOperation(value = "测试生产验证码", notes = "测试生产验证码")
    @GetMapping("/getCodeImg")
    public AjaxResult createImageCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        AjaxResult ajax = AjaxResult.success();
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        // 生成文字验证码
        String code = defaultKaptcha.createText();
        // 生成图片验证码
        BufferedImage image = defaultKaptcha.createImage(code);
        // 生成uuid
        String uuid = IdUtils.simpleUUID();
        // 验证信息
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
        // 这里我们使用redis缓存验证码的值，并设置过期时间为60秒
        redisCache.setCacheObject(verifyKey, code, 120, TimeUnit.SECONDS);
        // 转换流信息写出
        FastByteArrayOutputStream out = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", out);
        } catch (IOException e) {
            return AjaxResult.error(e.getMessage());
        }
        ajax.put("uuid", uuid);
        ajax.put("img", Base64.encode(out.toByteArray()));
        return ajax;
    }

    @ApiOperation(value = "测试登录接口", notes = "测试登录接口")
    @PostMapping("login")
    public ResultBean<?> login(@RequestBody LoginBody loginBody) throws Exception {
        if (StringUtils.isEmpty(loginBody)) {
            return ResultBean.VALIDATE(CodeEnum.PARAMETER_FORMAT_DOES_NOT_MATCH);
        }
        String token = sysLoginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(), loginBody.getUuid());

        return ResultBean.SUCCESS();
    }


    //@ApiOperation(value = "测试登录接口", notes = "测试登录接口")
    //@PostMapping("/login")
    //public ResultBean<?> login(@RequestBody @Valid SysUser sysUser) throws Exception {
    //    if (StringUtils.isEmpty(sysUser)) {
    //        return ResultBean.VALIDATE(CodeEnum.PARAMETER_FORMAT_DOES_NOT_MATCH);
    //    }
    //    return ResultBean.SUCCESS(shiroService.login(sysUser));
    //}

    @ApiOperation(value = "用户退出接口", notes = "用户退出接口")
    @PostMapping("/logout")
    public ResultBean<?> logout(@RequestBody @Valid SysUser sysUser) {
        if (StringUtils.isEmpty(sysUser)) {
            return ResultBean.VALIDATE(CodeEnum.PARAMETER_FORMAT_DOES_NOT_MATCH);
        }
        return ResultBean.SUCCESS(shiroService.logout(sysUser));
    }
}
